package com.example.fbi_text.Acitivity;

import static android.content.ContentValues.TAG;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.fbi_text.R;
import com.example.fbi_text.database.DBHelper;
import com.example.fbi_text.views.MainActivity;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

public class ChangeTextActivity extends AppCompatActivity {
    private EditText etTitle, etAuthor, etTime, etContent;
    private Button btnConfirm;
    private ImageView btnBack;
    private int newsId;

    // 定义回调接口
    public interface OnNewsUpdateListener {
        void onNewsUpdated();
    }

    // 静态监听器实例
    private static OnNewsUpdateListener listener;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.change_text);

        // 初始化控件
        etTitle = findViewById(R.id.et_text_title);
        etAuthor = findViewById(R.id.et_text_author);
        etTime = findViewById(R.id.et_text_time);
        etContent = findViewById(R.id.et_text_content);
        btnConfirm = findViewById(R.id.change_text_sure_button);
        btnBack = findViewById(R.id.change_text_back);

        // 接收传递的数据
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            etTitle.setText(extras.getString("news_title"));
            etAuthor.setText(extras.getString("news_author"));
            etTime.setText(extras.getString("news_time"));
            etContent.setText(extras.getString("news_content"));
            newsId = extras.getInt("news_id", -1);
        }

        // 返回按钮
        btnBack.setOnClickListener(v -> finish());
        etTime.setOnClickListener(v -> showDatePickerDialog());//为时间 EditText 添加点击事件

        // 确认按钮
        btnConfirm.setOnClickListener(v -> {
            String title = etTitle.getText().toString();
            String author = etAuthor.getText().toString();
            String time = etTime.getText().toString();
            String content = etContent.getText().toString();

            if (title.isEmpty() || content.isEmpty()) {
                Toast.makeText(this, "标题和内容不能为空", Toast.LENGTH_SHORT).show();
                return;
            }
            // 添加日期格式验证
            if (!time.isEmpty() && !isValidDate(time)) {
                Toast.makeText(this, "日期格式不正确，请使用 yyyy/MM/dd 格式", Toast.LENGTH_SHORT).show();
                return;
            }

            // 更新数据库
            DBHelper dbHelper = DBHelper.getInstance(this);
            boolean isUpdated = dbHelper.updateNewsById(newsId, title, author, time, content);

            if (isUpdated) {
                Log.d(TAG, "数据库更新成功，准备回调");
                // 通知监听器数据已更新
                if (listener != null) {
                    Log.d(TAG, "监听器存在，执行回调");
                    listener.onNewsUpdated();
                }else {
                    Log.e(TAG, "监听器为null，无法回调");
                }

                // 设置结果并关闭Activity
                setResult(RESULT_OK);
                Toast.makeText(this, "修改成功", Toast.LENGTH_SHORT).show();
                finish();
            } else {
                Toast.makeText(this, "修改失败", Toast.LENGTH_SHORT).show();
            }
        });
    }
    // 设置监听器
    public static void setOnNewsUpdateListener(OnNewsUpdateListener listener) {
        ChangeTextActivity.listener = listener;
    }

    // 清除监听器
    public static void removeOnNewsUpdateListener() {
        listener = null;
    }
    private boolean isValidDate(String dateStr) {
        // 定义你期望的日期格式，例如 "yyyy/MM/dd"
        String dateFormat = "yyyy/MM/dd";

        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat, Locale.getDefault());
        sdf.setLenient(false); // 设置为严格模式，不自动转换无效日期

        try {
            sdf.parse(dateStr);
            return true;
        } catch (ParseException e) {
            return false;
        }
    }
    private void showDatePickerDialog() {
        final Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);

        DatePickerDialog datePickerDialog = new DatePickerDialog(
                this,
                (view, selectedYear, selectedMonth, selectedDay) -> {
                    // 月份从0开始，所以要加1
                    String selectedDate = selectedYear + "/" + (selectedMonth + 1) + "/" + selectedDay;
                    etTime.setText(selectedDate);
                },
                year, month, day);

        datePickerDialog.show();
    }

}
